# 单例模式的定义：单例模式是指一个类只能创建一个实例，即单例模式，单例模式可以保证系统内存中该类只存在一个对象，
# 节省了系统资源，对于一些需要频繁创建销毁的对象，使用单例模式可以提高系统性能。
# 注意： python的模块就是天然的单例模式，因为模块在第一次导入时，会生成 .pyc 文件，当第二次导入时，就会直接加载 .pyc 文件，而不会再次执行模块代码。
def singleton_decorator(cls):
    instances = {}

    def wrapper(*args, **kwargs):
        if cls not in instances:
            instances[cls] = cls(*args, **kwargs)
        return instances[cls]

    return wrapper


class Singleton:
    _instance = None

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super().__new__(cls)
        return cls._instance

    @classmethod
    def get_instance(cls):
        if not cls._instance:
            cls._instance = cls()
        return cls._instance

# 使用hasattr()实现单例模式
class Singleton:
    _instance = None

    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, "_instance"):
            cls._instance = super().__new__(cls)
        return cls._instance


# s1 = Singleton()
# s2 = Singleton()
# print(s1 is s2)  # True
# print(id(s1))  # 140705739427840
# print(id(s2))  # 140705739427840

# s1 = Singleton.get_instance()
# s2 = Singleton.get_instance()
# print(s1 is s2)  # True
# print(id(s1))  # 140705739427840
# print(id(s2))  # 140705739427840

@singleton_decorator # 等价于 A = singleton_decorator(A) = wrapper(*args, **kwargs) = A(*args, **kwargs) = A()
class A:
    def test(self):
        print("test")

a1 = A()
a2 = A()
a1.test()
print(id(a1))  # 140705739427840
print(id(a2))  # 140705739427840
print(hasattr(a1, "test"))  # True

